<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="姓名"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="highQuery">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="onSale" :disabled="this.sels.length===0">批量上架</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="offSale" :disabled="this.sels.length===0">批量下架</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="pets" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="name" label="宠物名称" width="120" sortable>
			</el-table-column>
			<el-table-column prop="saleprice" label="价格" width="100" sortable>
			</el-table-column>
			<el-table-column prop="state" label="状态" width="100" sortable>
				<template scope="scope">
					<span style="color: green" v-if="scope.row.state==1">待领养</span>
					<span style="color: deepskyblue" v-else-if="scope.row.state==2">已被领养</span>
					<span style="color: red" v-else-if="scope.row.state==0">未上架</span>
				</template>
			</el-table-column>
			<el-table-column prop="petType.name" label="宠物品种类型" min-width="180" sortable>
			</el-table-column>
			<el-table-column prop="onsaletime" label="上架时间" min-width="180" sortable>
			</el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
						   :current-page="currentPage" :page-size="pageSize" :total="totals" style="float:right;">
			</el-pagination>
		</el-col>

		<!--添加和修改对话框-->
		<el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
				<el-form-item label="名称" prop="name">
					<el-input v-model="saveForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="价格" prop="sn">
					<el-input v-model="saveForm.saleprice" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="宠物类型" prop="sn">
					<el-input v-model="saveForm.petType.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="宠物描述" prop="sn">
					<el-input v-model="saveForm.petType.description" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="商品图片">
					<el-upload
							class="upload-demo"
							action="http://localhost:/dfs/upload"
							:on-remove="handleRemove"
							:on-success="handleSuccess"
							:limit="5"
							:file-list="fileList"
							list-type="picture">
						<el-button size="small" type="primary">点击上传</el-button>
						<div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
					</el-upload>
				</el-form-item>
				<el-form-item label="上架商铺">
					<el-select v-model="saveForm.shop" value-key="id" placeholder="请选择">
						<!--
                            v-for="item in cities" - 循环每一个员工对象
                            :label="item.username" - 指定要显示哪一个值
                            :value="item.value" - 用于点击提交时候传递到后端的数据
                            当你要绑定的时对象的时候，value-key
                        -->
						<el-option
								v-for="item in shops"
								:label="item.name"
								:value="item">
							<span style="float: left">{{ item.name }}</span>
							<span style="float: right; color: #8492a6; font-size: 13px">{{ item.tel }}</span>
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="预领须知" prop="orderNotice">
					<quill-editor
							v-model="saveForm.petDetail.adoptNotice"
							:options="editorOption"
					>
					</quill-editor>
				</el-form-item>
				<el-form-item label="简介" prop="intro">
					<quill-editor
							v-model="saveForm.petDetail.intro"
							:options="editorOption"
					>
					</quill-editor>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
    import util from '../../common/js/util'
    import quillConfig from '../../common/js/quill-config'
    import { quillEditor } from 'vue-quill-editor' //调用编辑器
    import 'quill/dist/quill.core.css'
    import 'quill/dist/quill.snow.css'
    import 'quill/dist/quill.bubble.css'



    export default {
        components: {
            quillEditor
        },
        data() {
            return {
                editorOption: quillConfig,
                filters: {
                    keyword: ''
                },
                fileList:[],
                pets: {},
                totals: 0,
                currentPage: 1,
                pageSize:5,
                listLoading: false,
                sels: [],//列表选中列
                title: "",
                masters:[],
                shops:[],
                types:[],
                //编辑模态框模型数据
                saveFormVisible: false,//编辑界面是否显示
                saveLoading: false,
                saveFormRules: {
                    name: [
                        { required: true, message: '请输入宠物姓名', trigger: 'blur' }
                    ],
                },
                //编辑界面数据清空
                saveForm: {
                    id: null,
                    name: '',
                    saleprice: 0,
                    state: 0,
                    shop: null,
					master:null,
					type:null,
					petType:{
                        id:null,
						name:'',
						description:''
					},
                    petDetail:{
                        id:null,
                        adoptNotice:'',
                        intro:''
                    },
                },

                //新增模态框模型
                saveFormVisible: false,//新增界面是否显示
                saveLoading: false,
                saveFormRules: {
                    name: [
                        { required: true, message: '请输入宠物姓名', trigger: 'blur' }
                    ],
                },
            }
        },
        methods: {
            //批量上架
            onSale: function () {
                var ids = this.sels.map(item => item.id);
                this.$confirm('确认上架选中商品吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    this.$http.put("/pet/onSale",ids)
                        .then(res=>{
                            this.listLoading = false;
                            if (res.data.success) {
                                this.$message({
                                    message:"操作成功",
                                    type:'success'
                                })
                                this.currentPage = 1;
                                this.getPets();
                            } else{
                                this.$message({
                                    message:res.data.msg,
                                    type:'error'
                                })
                            }
                        })
                        .catch(res=>{
                            alert("系统异常！")
                        })
                }).catch(() => {

                });
            },
            //批量下架
            offSale: function () {
                var ids = this.sels.map(item => item.id);
                this.$confirm('确认上架选中商品吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    this.$http.put("/pet/offSale",ids)
                        .then(res=>{
                            this.listLoading = false;
                            if (res.data.success) {
                                this.$message({
                                    message:"操作成功",
                                    type:'success'
                                })
                                this.currentPage = 1;
                                this.getPets();
                            } else{
                                this.$message({
                                    message:res.data.msg,
                                    type:'error'
                                })
                            }
                        })
                        .catch(res=>{
                            alert("系统异常！")
                        })
                }).catch(() => {

                });
            },
            // 上传图片
            handleSuccess(response, file, fileList){
                // 定义临时变量接收
                let result = ''
                // 循环文件列表
                for (let i=0;i <fileList.length; i++) {
                    // 因为下标从0开始，所以达到长度-1 表示最后一个所以
                    if (i==fileList.length -1) {
                        // fileList[i].response.resultObject 文件的路径
                        result+= fileList[i].response.resultObject;
                    } else {
                        result+=fileList[i].response.resultObject+",";
                    }
                }
                // 将result赋值给resources
                this.saveForm.resources = result;
            },
            //删除附件
            handleRemove(file, fileList) {
                var filePath =file.response.resultObj;
                this.$http.delete("/dfs?path="+filePath)
                    .then(res=>{
                        if(res.data.success){
                            this.$message({
                                message: '删除成功!',
                                type: 'success'
                            });
                        }else{
                            this.$message({
                                message: '删除失败!',
                                type: 'error'
                            });
                        }
                    })
            },
            highQuery(){
                this.currentPage = 1;
                this.getPets();
            },
            handleCurrentChange(val) {
                this.currentPage = val;
                this.getPets();
            },
            //获取宠物列表
            getPets() {
                let para = {
                    currentPage: this.currentPage,
                    pageSize: this.pageSize,
                    keyword: this.filters.keyword
                };
                this.listLoading = true;
                this.$http.post("/pet",para)
                    .then(res=>{
                        //1.去掉忙等框
                        this.listLoading = false;
                        //2.给模型数据pets赋值
                        this.pets = res.data.data;
                        //3.给模型数据totals赋值
                        this.totals = res.data.totals;
                    })
                    .catch(res=>{
                        alert("系统错误");
                    })
            },
            //删除
            handleDel: function (index, row) {
                this.$confirm('确认删除该记录吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    let para = "/pet/" + row.id;
                    this.$http.delete(para)
                        .then(res=>{
                            this.listLoading = false;
                            if(res.data.success) {
                                this.$message({
                                    message:"删除成功",
                                    type:'success'
                                })
                                //如果删除的是本页最后一条且当前页不是第一页，就跳转到上一页
                                if(this.currentPage>1 && (this.totals - 1)% this.pageSize == 0){
                                    this.currentPage = this.currentPage -1
                                }
                                this.getPets();
                            } else {
                                this.$message({
                                    message:res.data.msg,
                                    type:'error'
                                })
                            }
                        })
                        .catch(res=>{
                            alert("系统异常")
                        })
                }).catch(() => {

                });
            },
            //显示编辑界面
            handleEdit: function (index, row) {
                this.title = "编辑"
                this.saveFormVisible = true;
                this.getShops()
                this.saveForm = Object.assign({}, row);

                this.fileList = []
                // 通过row.resources 获取文件列表的路径
                if(row.resources) {
                    // 通过,分割路径
                    let arr = row.resources.split(",");
                    // 循环添加到fileList中
                    for (var i = 0; i < arr.length; i++) {
                        //把对象放到数组里面
                        this.fileList.push({
                            name: '?.jpg',
                            // 服务器中的地址+路径
                            url: 'http://115.159.217.249:8888' + arr[i]
                        })
                    }
                }

            },
            //显示新增界面
            handleAdd: function () {
                this.title = "新增"
                this.saveFormVisible = true;
                this.getShops()
                this.saveForm = {
                    id: null,
                    name: '',
                    saleprice: 0,
                    state: 0,
                    shop: null,
                    master:null,
                    type:null,
                    petType:{
                        id:null,
                        name:'',
                        description:''
                    },
                    petDetail:{
                        id:null,
                        adoptNotice:'',
                        intro:''
                    },
                };
            },
            //点击新增和修改的提交按钮时触发的方法
            saveSubmit: function () {
                this.$refs.saveForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.saveLoading = true;
                            // 克隆表单数据到空{}，防止原对象数据被修改
                            let para = Object.assign({}, this.saveForm);
                            this.$http.put("/pet",para)
                                .then(res=>{
                                    this.saveLoading = false;
                                    if (res.data.success) {
                                        this.$message({
                                            message: '提交成功',
                                            type: 'success'
                                        })
										// 重置表单
                                        this.$refs['saveForm'].resetFields();
                                        // 关闭忙等框
                                        this.saveFormVisible = false;
                                        // 调用列表方法刷新界面
                                        this.getPets();
                                    } else {
                                        this.$message({
                                            message: res.data.msg,
                                            type: 'error'
                                        });
                                    }
                                })
                                .catch(res=>{
                                    alert("系统异常")
                                })

                        });
                    }
                });
            },

            selsChange: function (sels) {
                this.sels = sels;
            },
            //批量删除
            batchRemove: function () {
                var ids = this.sels.map(item => item.id);
                this.$confirm('确认删除选中记录吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    this.$http.patch("/pet",ids)
                        .then(res=>{
                            this.listLoading = false;
                            if (res.data.success) {
                                this.$message({
                                    message:"操作成功",
                                    type:'success'
                                })
                                this.currentPage = 1;
                                this.getPets();
                            } else{
                                this.$message({
                                    message:res.data.msg,
                                    type:'error'
                                })
                            }
                        })
                        .catch(res=>{
                            alert("系统异常！")
                        })
                }).catch(() => {

                });
            },
            getShops(){
                this.$http.get("/pet/shops")
                    .then(res=>{
                        if (res) {
                            this.shops = res.data;
                        }
                    })
            },
            getMasters(){
                this.$http.get("/pet/masters")
                    .then(res=>{
                        if (res) {
                            this.masters = res.data;
                        }
                    })
            },
            getTypes(){
                this.$http.get("/pet/types")
                    .then(res=>{
                        if (res) {
                            this.types = res.data;
                        }
                    })
            },
        },
        mounted() {
            this.getPets();
        }
    }

</script>

<style scoped>

</style>